package com.zookeeper.lock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.concurrent.TimeoutException;

/**
 * Created by lee on 2016/11/28.
 */
class ZooKeeperLockWatcher implements Watcher {

    Log log = LogFactory.getLog(getClass());
    private boolean isSyncConnected;

    public void process(WatchedEvent event) {
        if (event.getState() == Event.KeeperState.SyncConnected) {
            synchronized (this) {
                isSyncConnected = true;
                this.notifyAll();
            }
        }
        if (event.getType() == Event.EventType.NodeChildrenChanged) {
            synchronized (this) {
                this.notifyAll();
            }
        }
    }

    public void awaitSyncConnected(int timeout) throws InterruptedException, TimeoutException {
        synchronized (this) {
            while (!isSyncConnected) {
                if(Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }
                this.wait(timeout);
            }
        }
        if(! isSyncConnected) {
            throw new TimeoutException("Connection zooKeeper timed out!");
        }
    }
}